<template>
  <view class="mind-map-container">
    <canvas
      canvas-id="mindMapCanvas"
      id="mindMapCanvas"
      type="2d"
      :style="{ width: width + 'px', height: height + 'px' }"
	  @touchstart="onTouchStart"
	  @touchmove="onTouchMove"
	  @touchend="onTouchEnd"
    />
  </view>
</template>

<script setup>
import { ref, onMounted, watch, getCurrentInstance } from 'vue'
import { drawMindMap, createDragZoomController, computeSubtreeHeight } from './mindmap.js'

// ============ props ============
const props = defineProps({
  data: { // 思维导图数据
    type: Object,
    required: true
  },
  width: { // 画布宽
    type: Number,
    default: 600
  },
  height: { // 画布高
    type: Number,
    default: 400
  }
})

const instance = getCurrentInstance()
const proxy = instance?.proxy

const offsetX = ref(0)
const offsetY = ref(0)
const scale = ref(1) // <<< 增加 scale

// ============ 渲染 ============
function render() {
	uni.createSelectorQuery()
	    .in(proxy)
	    .select('#mindMapCanvas')
	    .node(res => {
	      const canvas = res.node
	      const ctx = canvas.getContext('2d')
		  ctx.resetTransform() // <<< reset
	      ctx.clearRect(0, 0, props.width, props.height)
		   // ========== scale 和 translate 生效 ==========
		  ctx.translate(offsetX.value, offsetY.value)
		  ctx.scale(scale.value, scale.value)
		  computeSubtreeHeight(props.data, ctx, 0) 
		  // initializeMindMap(props.data,ctx,0,0)
	      drawMindMap(ctx, props.data, 0, 0, 0, offsetX.value, offsetY.value)
	    })
	    .exec()
}

// 使用封装好的拖动控制器
const { onTouchStart, onTouchMove, onTouchEnd } = createDragZoomController(offsetX, offsetY, scale, render)

// ============ 监听 data 变化 ============
watch(() => props.data, () => {
  render()
}, { deep: true })

onMounted(() => {
  render()
})
</script>

<style scoped>
.mind-map-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
